package client_commands;

import java.util.StringTokenizer;

import client.ClientApplication;
import client.ClientBindObject;
import client_tree.User;

public class SERV_CHSTATUSCommand extends Command {


	public SERV_CHSTATUSCommand(String parameter) {
		setCode(SERV_CHSTATUS);
		setParameter(parameter);
	}
	
	
	@Override
	public boolean executeCommand(ClientApplication theApp) {
		
		StringTokenizer tokens = new StringTokenizer(getParameter());
		
		String username = tokens.nextToken();
		String newStatus = tokens.nextToken();
		String nickname = tokens.nextToken();
		String email = tokens.nextToken();
		String avatar = tokens.nextToken();

		User user = theApp.getClientModel().getOnlineModel().getUserByUsername(username);;

		if (user == null) {
			user = theApp.getClientModel().getOfflineModel().getUserByUsername(username);;
		}
		
		if (user == null) {
			return false;
		}
		
		int status = user.getStatus();
		
		for (int i = 0; i < STATUS_NAMES.length; i++) {
			if ( newStatus.equals(STATUS_NAMES[i]) ) {
				status = i;
			}
		}

		
		
		if ( status == INVISIBLE_STATUS || status == OFFLINE_STATUS ) {
			setUserInfo(user, status, nickname, email, avatar);
//			user.setStatus(status);
			theApp.getClientModel().addUser(user);
			
			if (status == OFFLINE_STATUS) {
				if ( ClientApplication.clientBinding.get(username) != null ) {
					
					ClientBindObject cbo = ClientApplication.clientBinding.get(username);
					if (cbo.getDialog() != null) {
						cbo.getDialog().setConnection(null);
						cbo.getDialog().setSendButtonRights(false);
					}
					
					cbo.getConnection().writeData( Long.toString(cbo.getConnection().getConnectionID()) );
					
					try {
						Thread.sleep(1000);
					}
					catch (InterruptedException ie) {
						ie.printStackTrace();
					}
					
					cbo.getConnection().quitConnection();
					cbo.setConnection(null);
				}
			}
		}
		else {
			if ( user.getStatus() == INVISIBLE_STATUS || user.getStatus() == OFFLINE_STATUS ) {
				setUserInfo(user, status, nickname, email, avatar);
//				user.setStatus(status);
				theApp.getClientModel().addUser(user);
				
				ClientBindObject cbo = ClientApplication.clientBinding.get(username);		
				
				if (cbo != null && cbo.getDialog() != null) {
					cbo.getDialog().setSendButtonRights(true);
				}
			}
			else {
				setUserInfo(user, status, nickname, email, avatar);
//				user.setStatus(status);
				theApp.getWindow().refreshTree();
			}
		}
		
		return true;
	}
	
	
	private void setUserInfo(User user, int status, String nickname, String email, String avatar) {
		user.setStatus(status);
		user.setNickname(nickname);
		user.setEmail(email);
		user.setAvatar(avatar);
	}
	
}
